/**
 * 将树数据转化为平铺数据
 * @param treeData :树状数组
 * @param childKey :子节点键值
 * @returns {*[]}
 */
export function treeToTile(treeData, childKey = "children") {
  let arr = [];
  const expanded = data => {
    if (data && data.length > 0) {
      data
        .filter(d => d)
        .forEach(e => {
          arr.push(e);
          expanded(e[childKey] || []);
        });
    }
  };
  expanded(treeData);
  return arr;
}

/**
 * 树节点查询
 * @param tree 树状数组
 * @param id 节点ID
 * @param key 节点ID键值
 * @returns {*}
 */
export function breadthQuery(tree, id, key = "id") {
  let stark = [];
  stark = stark.concat(tree);
  while (stark.length) {
    let temp = stark.shift();
    if (temp.children) {
      stark = stark.concat(temp.children);
    }
    if (temp[key] === id) {
      return temp;
    }
  }
}

/**
 * 森林路径查询
 * @param value :节点ID
 * @param key :节点ID对应键值
 * @param arr :树状数组
 * @returns {*[]}
 */
export function getPathByKey(value, key, arr) {
  let temppath = [];
  try {
    const getNodePath = node => {
      temppath.push(node);
      //找到符合条件的节点，通过throw终止掉递归
      if (node[key] === value) {
        throw "GOT IT!";
      }
      if (node.children && node.children.length > 0) {
        for (var i = 0; i < node.children.length; i++) {
          getNodePath(node.children[i]);
        }
        //当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
        temppath.pop();
      } else {
        //找到叶子节点时，删除路径当中的该叶子节点
        temppath.pop();
      }
    };
    for (let i = 0; i < arr.length; i++) {
      getNodePath(arr[i]);
    }
  } catch (e) {
    return temppath;
  }
}
